package com.zhaosc.invoke;

import com.alibaba.fastjson.JSONObject;
import com.zhaosc.configbean.Reference;
import com.zhaosc.loadbalance.LoadBalance;
import com.zhaosc.loadbalance.NodeInfo;
import com.zhaosc.netty.NettyUtil;

public class NettyInvoke implements Invoke {

	@Override
	public String invoke(Invocation invocation) throws Exception {
		try {
			Reference reference=invocation.getReference();
			String loadBalance=reference.getLoadBalance();
			
			 LoadBalance loadbalanceBean =reference.getLoadBalances().get(loadBalance);
			
			 NodeInfo nodeInfo=loadbalanceBean.doSelect(reference.getRegistryInfo());
			 
			 JSONObject sendParam=new JSONObject();
			 sendParam.put("methodName", invocation.getMethod().getName());
			 sendParam.put("methodParams", invocation.getParams());
			 sendParam.put("serviceId", reference.getId());
			 sendParam.put("paramTypes", invocation.getMethod()
			         .getParameterTypes());
			 
			 return NettyUtil.sendMsg(nodeInfo.getHost(),
					 nodeInfo.getPort(),
					 sendParam.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
         
	}

}
